package com.google.code.gwtquickstartplugin;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.io.BufferedReader;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

import java.io.IOException;
import java.io.File;
import java.io.InputStreamReader;

/**
 * Generates JavaScript files from <code>*.client.*</code>
 * packages and merges remote services registered
 * in <code>&lt;Module&gt;</code>.gwt.xml module
 * definitions with the projects <code>web.xml</code>file.
 *
 * @author Brad Rydzewski
 * @author Carlos D. Morales
 * @goal package
 * @phase package
 */
public class GwtQuickstartPluginMojo
        extends AbstractMojo {

    /**
     * Indicates if the plugin should merge the gwt Module
     * with the web.xml file to create necessary servlets
     *
     * @parameter default-value="true"
     */
    private boolean mergeWebXml;
    /**
     * Path to local GWT installation.
     *
     * @parameter default-value="%GWT_HOME%"
     */
    private String gwtHomeDirectoryPath;
    /**
     * The path to the module (<code>&lt;Module&gt;</code>.gwt.xml)
     * file with the module metadata details.
     *
     * @parameter default-value="com.google.code.MyTestModule"
     */
    private String gwtModule;
    /**
     * The directory where the webapp is built.
     *
     * @parameter expression="${project.build.directory}/${project.build.finalName}"
     * @required
     */
    private String webappDirectory;
    /**
     * The path to the project root.
     *
     * @parameter expression="${basedir}"
     */
    private String projectRoot;

    private String buildCommandString(String projectRoot) {
        return new StringBuffer().append("cmd /c java -cp \"").append(projectRoot).append("\\src\\main\\java;bin;").append("\"").append(gwtHomeDirectoryPath).append("\"").append("\\gwt-user.jar;").append("\"").append(gwtHomeDirectoryPath).append("\"").append("\\gwt-dev-windows.jar\"").append(" com.google.gwt.dev.GWTCompiler ").append("-out \"").append(webappDirectory).append("\" %* ").append(gwtModule).toString();
    }

    public void execute() throws MojoExecutionException, MojoFailureException {
        try {
            String command = buildCommandString(projectRoot);
            getLog().info("Executing command [" + command + "]");

            Process process = Runtime.getRuntime().exec(command, null, new File(projectRoot));

            String line = "";
            BufferedReader input =
                    new BufferedReader(new InputStreamReader(process.getInputStream()));

            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
            input.close(); //need a finally to ensure closed?

            getLog().info(
                    "Command just finished execution.");

            if (mergeWebXml) {
                getLog().info("Merging the web.xml file...");
                GwtModuleToWebXmlMergingHelper helper =
                        new GwtModuleToWebXmlMergingHelper(getLog(), gwtModule,
                        projectRoot);
                helper.mergeGwtModuleToWebXml(webappDirectory, gwtModule);
                getLog().info("File merged.");
            } else {
                getLog().info("Merge with Web.xml setting = false");
            }



        } catch (IOException e) {
            throw new MojoFailureException(e, e.getMessage(), e.getMessage());
        } //catch (InterruptedException e) {
    //   throw new MojoFailureException(e, e.getMessage(), e.getMessage());
    //}
    }
}